package com.chenglai.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.chenglai.commonutils.common.DateFormatHelper;
import com.chenglai.commonutils.common.Result;
import com.chenglai.seckill.dao.GroupOnDetailMapper;
import com.chenglai.seckill.dao.GroupOnInfoMapper;
import com.chenglai.seckill.entity.MainOrder;
import com.chenglai.seckill.feign.GoodsService;
import com.chenglai.seckill.feign.OrderService;
import com.chenglai.seckill.feign.PayService;
import com.chenglai.seckill.pojo.GroupOnDetail;
import com.chenglai.seckill.pojo.GroupOnInfo;
import com.chenglai.seckill.rabbitmq.MqServer;
import com.chenglai.seckill.service.GroupOnInfoService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类描述：
 *
 * @Author rxh
 * @Date 2023/11/27 10:42
 */
@Service
public class GroupOnInfoServiceImpl implements GroupOnInfoService {

    @Resource
    private GroupOnInfoMapper groupOnInfoMapper;
    @Resource
    private GroupOnDetailMapper groupOnDetailMapper;
    @Resource
    private OrderService orderService;
    @Resource
    private PayService payService;
    @Resource
    private GoodsService goodsService;

    @Resource
    private RedisTemplate redisTemplate;
    private MqServer mqServer;

    @Override
    public List<GroupOnInfo> getGroupOnInfoList(Integer shopId, Integer userId) {
        Example example = new Example(GroupOnInfo.class);
        Example.Criteria criteria = example.createCriteria();
        if (shopId != null)
            criteria.andEqualTo("shopId", shopId);
        if (userId != null)
            criteria.andEqualTo("userId", userId);
        example.orderBy("groupId").desc();
        List<GroupOnInfo> list = groupOnInfoMapper.selectByExample(example);
        //查询团购详情
        list.stream().forEach(map -> {
            List<GroupOnDetail> detailList = groupOnDetailMapper.getDetailList(map.getGroupInfoId());
            map.setDetailList(detailList);
        });
        return list;
    }

    @Override
    public Integer editGroupOnInfo(GroupOnInfo groupOnInfo) {
        if (groupOnInfo.getGroupInfoId() == null) {
            String time = DateFormatHelper.currentTimes();
            groupOnInfo.setStartTime(time);
            //结束时间固定几分钟还是怎么样根据需求更改，我这里先写固定3分钟   2023-11-17 11:05:00
            try {
                groupOnInfo.setEndTime(DateFormatHelper.getTime(time, 3));
            } catch (Exception e) {
                e.printStackTrace();
            }
            groupOnInfo.setStatus(0);
            //返回主键ID
            Integer i = groupOnInfoMapper.insert(groupOnInfo);
            return i;
        } else {
            Integer i = groupOnInfoMapper.updateByPrimaryKeySelective(groupOnInfo);
            return i;
        }
    }

    @Override
    public void delGroupOnInfo(Integer groupId) {
        groupOnInfoMapper.deleteByPrimaryKey(groupId);
    }

    @Override
    public GroupOnInfo detail(Integer groupId) {
        GroupOnInfo groupOnInfo = groupOnInfoMapper.selectByPrimaryKey(groupId);
        List<GroupOnDetail> list = groupOnDetailMapper.getDetailList(groupId);
        groupOnInfo.setDetailList(list);
        return groupOnInfo;
    }

    @Override
    public void groupOnLogic(Map<String, Object> map) {
        //改用RabbitMQ方式
        mqServer.sendGroupOnMessage(map);
    }

    @Override
    public void groupOnEnd(Integer groupId) {
        //修改主表状态
        groupOnInfoMapper.updateStatus(1, groupId);
        //执行退款
        List<GroupOnDetail> detailList = groupOnDetailMapper.getDetailList(groupId);
        for (int i = 0; i < detailList.size(); i++) {
            String orderNum = detailList.get(i).getOrderNum();
            //根据orderNum查询订单退款需要的参数
            Map<String,Object> param = orderService.queryRefundParam(orderNum);
            String transactionId = (String) param.get("transactionId");
            Integer shopId = (Integer) param.get("shopId");
            Double totalNum = (Double) param.get("totalSum");
            Double refundFee = (Double) param.get("realSum");
            payService.refund(transactionId,shopId,totalNum,refundFee,"来自团购失败的退款");
        }


    }

    @Override
    public Result listGroupGoods(Integer shopId) {
        return goodsService.listGroupGoods(shopId);
    }
    @Override
    public Result startGroup(MainOrder mainOrder, Integer groupId,Integer flag,Integer groupNum) {
        if(flag==1) {
            //开团
            GroupOnInfo groupOnInfo = new GroupOnInfo();
            groupOnInfo.setShopId(mainOrder.getShopId());
            groupOnInfo.setGoodsId(mainOrder.getOrderList().get(0).getProductId());
            groupOnInfo.setUserId(mainOrder.getUserId());
//            Integer gid = editGroupOnInfo(groupOnInfo);
//            redisTemplate.opsForValue().decrement("group_"+)

            redisTemplate.opsForHash().put("group_" + mainOrder.getUserId().toString() + ":" + groupId.toString(), "groupM_" + groupId.toString(), JSON.toJSONString(groupOnInfo));

        }
        //添加到队列
        //生成订单，添加到队列
        return goodsService.toAddMainOrders(mainOrder);
    }

    @Override
    public Map addGroupOnOrDetail(Map map) {
        Integer groupNum = Integer.parseInt(map.get("groupNum").toString());
        String userId = map.get("userId").toString();
        String groupId = map.get("groupId").toString();
        String orderNum = map.get("orderNum").toString();

        Integer flag = Integer.parseInt(map.get("flag").toString());
        if(flag==0){
            //开团
            GroupOnInfo info = JSON.parseObject((String)redisTemplate.opsForHash().get("group_"+userId+":"+groupId,"groupM_"+groupId),GroupOnInfo.class);
            groupOnInfoMapper.insertSelective(info);
            groupId = info.getGroupInfoId().toString();
            redisTemplate.opsForValue().set("groupInfo_"+groupId,groupNum);
//            redisTemplate.opsForHash().delete("group_"+userId,"groupM_"+groupId);
            //清空开团信息
            redisTemplate.opsForHash().delete("group_"+userId+":"+groupId);
        }
        //添加详情
        GroupOnDetail detail = new GroupOnDetail();
        detail.setOrderNum(orderNum);
        detail.setGroupId(Integer.parseInt(groupId));
        detail.setUserId(Integer.parseInt(userId));
        groupOnDetailMapper.insertSelective(detail);
        redisTemplate.opsForValue().decrement("groupInfo_"+groupId,1);
        Integer num = Integer.parseInt(redisTemplate.opsForValue().get("groupInfo_"+groupId).toString());
        //修改订单的groupId
        orderService.updateOrderGroup(orderNum,Integer.parseInt(groupId));
        if(num==0){
            //团满,更新主团信息
            GroupOnInfo infos = new GroupOnInfo();
            infos.setGroupInfoId(Integer.parseInt(groupId));
            infos.setStatus(2);
            groupOnInfoMapper.updateByPrimaryKeySelective(infos);

            //将订单改为开团成功
            orderService.updateOrderGroupStatus(Integer.parseInt(groupId),1);
        }


        Map maps = new HashMap();
        maps.put("flag","success");
        maps.put("msg","开团成功");
        return maps;
    }

}
